import sys
from pathlib import Path
import json

sys.path.append(str(Path(__file__).parent.parent))
from reqapi.api import BaseApi
from reqapi.models.token_verify import TokenVerifyRequest, TokenVerifyResponse

class TokenVerifyApi(BaseApi):
    """Token验证API"""
    
    def verify_token(self, request: TokenVerifyRequest):
        """验证Token
        
        Args:
            request: Token验证请求对象
            
        Returns:
            TokenVerifyData: Token验证响应数据
            
        Raises:
            Exception: 请求失败或业务处理失败时抛出异常
        """
        # API端点
        endpoint = "/api/youpin/token/verify"
        url = f"{self.BASE_URL}{endpoint}"
        
        # 构建请求数据
        request_data = {
            "token": request.token,
            "Sessionid": request.Sessionid
        }
        
        # 获取请求头
        headers = self.common_headers
        
        print("=" * 50)
        print("Token验证API - 请求URL:")
        print(url)
        print("\nToken验证API - 请求头:")
        for key, value in headers.items():
            print(f"{key}: {value}")
        print("\nToken验证API - 请求体:")
        print(json.dumps(request_data, indent=4, ensure_ascii=False))
        print("=" * 50)

        # 统一用拦截器处理请求和响应
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            # 可选：如需转为TokenVerifyResponse对象
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            response_obj = TokenVerifyResponse.from_dict(result)
            return response_obj
        except Exception as e:
            print(f"请求失败: {e}")
            return None


def main():
    """测试Token验证API"""
    try:
        # 从数据库获取账号信息
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
            
        if not account:
            print("无法获取ID为1的账号")
            return
            
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = TokenVerifyApi(
            device_token=device_id,
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 创建请求对象
        request = TokenVerifyRequest(
            token=auth_token,
            Sessionid=device_id
        )
        
        # 发送请求
        result = api.verify_token(request)
        
        # 打印结果
        print("Token验证结果:")
        if result and hasattr(result, 'data') and result.data:
            print(f"是否有效: {getattr(result.data, 'result', None)}")
            print(f"消息: {getattr(result.data, 'msg', None)}")
        else:
            print("验证失败或无返回数据")

    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()
